package com.ja.openchat.ui.chat.group.adapter;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.JsonObject;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.group.LocalMessageInfo;
import com.zy.openchat.core.model.message.MessageInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;

public class GroupSendModule {
    private List<Observable<TgResponse>> observables = new ArrayList();
    private List<Long> userIds;
    private LocalMessageInfo messageInfo;
    private Context mContext;
    public GroupSendModule(Context context,List<Long> userIds, LocalMessageInfo messageInfo) {
        this.userIds = userIds;
        this.messageInfo = messageInfo;
        this.mContext = context;
    }

    private ObservableEmitter<List<Observable<TgResponse>>> mEmitter = null;

    private MessageInfo handleMessageInfo = null;
    private boolean isHandleRemoteFile = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(TgEvent tg_event) {
        switch (tg_event.event){
            case EUser_Td_Chat_Send_Message_Fail:
                if(tg_event.data!=null&&tg_event.data instanceof MessageInfo&&tg_event.dataEx instanceof Long) {
                    long oldMesssageId = (Long) tg_event.dataEx;
                    MessageInfo message = (MessageInfo) tg_event.data;
                    if (handleMessageInfo == null || handleMessageInfo.id != oldMesssageId) {
                        return;
                    }
                    isHandleRemoteFile = true;
                    onDestory();
                    observables.clear();
                    for(Long userId:userIds){
                        observables.add(new Observable<TgResponse>() {
                            @Override
                            protected void subscribeActual(Observer<? super TgResponse> observer) {
                                observer.onNext(new TgResponse(false,"发送失败"));
                                observer.onComplete();
                            }
                        });
                    }
                    mEmitter.onNext(observables);
                    mEmitter.onComplete();
                }
                break;
            case EUser_Td_Chat_Send_Message_Success:
                if(tg_event.data!=null&&tg_event.data instanceof MessageInfo&&tg_event.dataEx instanceof Long){
                    long oldMesssageId = (Long) tg_event.dataEx;
                    MessageInfo message = (MessageInfo)tg_event.data;
                    if(handleMessageInfo==null||handleMessageInfo.id!=oldMesssageId){
                        return;
                    }
                    final String remoteFileId = message.getRemoteFileId();
                    if(!isHandleRemoteFile&&!TextUtils.isEmpty(remoteFileId)){
                        isHandleRemoteFile = true;
                        onDestory();
                        observables.clear();
                        observables.add(new Observable<TgResponse>() {
                            @Override
                            protected void subscribeActual(Observer<? super TgResponse> observer) {
                                observer.onNext(new TgResponse(true,"发送成功"));
                                observer.onComplete();
                            }
                        });

                        for(int i = 1; i<userIds.size();i++){
                            long userId = userIds.get(i);
                            observables.add(new Observable<TgResponse>() {
                                @Override
                                protected void subscribeActual(Observer<? super TgResponse> observer) {
                                    TgResultBlock<TgResponse> tgResultBlock = new TgResultBlock<TgResponse>() {
                                        @Override
                                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                                            observer.onNext(obj);
                                            observer.onComplete();
                                        }

                                        @Override
                                        public void onTimeout(Map<String, Object> request) {
                                            observer.onNext(new TgResponse(false, "发送超时"));
                                            observer.onComplete();
                                        }
                                    };
                                    if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Photo) {
                                        TelegramManager.getTelegramManager().sendPhotoMessage(mContext, userId, remoteFileId ,(float) messageInfo.width, (float) messageInfo.height, messageInfo.countDown, tgResultBlock);
                                    }else if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Animation){
                                        TelegramManager.getTelegramManager().sendGifMessage(mContext,userId,TelegramManager.buildRemoteDic(remoteFileId),messageInfo.width,messageInfo.height,messageInfo.countDown,tgResultBlock);
                                    }else if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Video){
                                        TelegramManager.getTelegramManager().sendVideoMessage(mContext, userId, remoteFileId, (float) messageInfo.width, (float) messageInfo.height, messageInfo.duration,messageInfo.countDown, tgResultBlock);
                                    }else if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Audio){
                                        TelegramManager.getTelegramManager().sendAudioMessage(mContext,userId,TelegramManager.buildRemoteDic(remoteFileId),(int)messageInfo.duration,messageInfo.countDown,tgResultBlock);
                                    }
                                }
                            });
                        }
                        mEmitter.onNext(observables);
                        mEmitter.onComplete();
                    }
                }
                break;
            case EUser_Td_Chat_New_Message:
                if(tg_event.data!=null&&tg_event.data instanceof MessageInfo) {
                    MessageInfo messageInfo = (MessageInfo) tg_event.data;
                    if(handleMessageInfo==null){
                        handleMessageInfo = messageInfo;
                    }

                }
                break;
        }
    }


    public Observable<List<Observable<TgResponse>>> sendMessage(){
        return Observable.create(new ObservableOnSubscribe<List<Observable<TgResponse>>>() {
            @Override
            public void subscribe(ObservableEmitter<List<Observable<TgResponse>>> emitter) throws Exception {
                mEmitter = emitter;
                if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Text){
                    for(Long userId:userIds){
                        observables.add(new Observable<TgResponse>() {
                            @Override
                            protected void subscribeActual(Observer<? super TgResponse> observer) {
                                TelegramManager.getTelegramManager().sendTextMessage(mContext, userId, messageInfo.content, 0, null, messageInfo.countDown, new TgResultBlock<TgResponse>() {
                                    @Override
                                    public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                                        observer.onNext(obj);
                                        observer.onComplete();
                                    }

                                    @Override
                                    public void onTimeout(Map<String, Object> request) {
                                        observer.onNext(new TgResponse(false, "发送超时"));
                                        observer.onComplete();
                                    }
                                });
                            }
                        });
                    }
                    emitter.onNext(observables);
                    emitter.onComplete();
                }else{
                    TgResultBlock<TgResponse> tgResultBlock = userIds.size()==1?null:new TgResultBlock<TgResponse>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                            if(obj!=null&&!obj.ok){
                                onDestory();
                                emitter.onError(new Throwable("发送失败，请稍后重试"));
                                emitter.onComplete();
                            }
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {
                            onDestory();
                            emitter.onError(new Throwable("发送超时，请稍后重试"));
                            emitter.onComplete();
                        }
                    };
                    if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Photo){
                        if(userIds.size()==1){
                            observables.add(new Observable<TgResponse>() {
                                @Override
                                protected void subscribeActual(Observer<? super TgResponse> observer) {
                                    TelegramManager.getTelegramManager().sendPhotoMessage(mContext, userIds.get(0), messageInfo.content, messageInfo.width, messageInfo.height, messageInfo.countDown,new TgResultBlock<TgResponse>() {
                                        @Override
                                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                                            observer.onNext(obj);
                                            observer.onComplete();
                                        }

                                        @Override
                                        public void onTimeout(Map<String, Object> request) {
                                            observer.onNext(new TgResponse(false, "发送超时"));
                                            observer.onComplete();
                                        }
                                    });
                                }
                            });
                            emitter.onNext(observables);
                            emitter.onComplete();
                        }else{
                            EventBus.getDefault().register(GroupSendModule.this);
                            TelegramManager.getTelegramManager().sendPhotoMessage(mContext, userIds.get(0), messageInfo.content, messageInfo.width, messageInfo.height, messageInfo.countDown, tgResultBlock);
                        }
                    }else if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Animation){
                        if(userIds.size()==1){
                            observables.add(new Observable<TgResponse>() {
                                @Override
                                protected void subscribeActual(Observer<? super TgResponse> observer) {
                                    TelegramManager.getTelegramManager().sendGifMessage(mContext, userIds.get(0), messageInfo.content, messageInfo.width, messageInfo.height, messageInfo.countDown,new TgResultBlock<TgResponse>() {
                                        @Override
                                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                                            observer.onNext(obj);
                                            observer.onComplete();
                                        }

                                        @Override
                                        public void onTimeout(Map<String, Object> request) {
                                            observer.onNext(new TgResponse(false, "发送超时"));
                                            observer.onComplete();
                                        }
                                    });
                                }
                            });
                            emitter.onNext(observables);
                            emitter.onComplete();
                        }else{
                            EventBus.getDefault().register(GroupSendModule.this);
                            TelegramManager.getTelegramManager().sendGifMessage(mContext, userIds.get(0), messageInfo.content, messageInfo.width, messageInfo.height, messageInfo.countDown, tgResultBlock);
                        }
                    }else if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Video){
                        if(userIds.size()==1){
                            observables.add(new Observable<TgResponse>() {
                                @Override
                                protected void subscribeActual(Observer<? super TgResponse> observer) {
                                    TelegramManager.getTelegramManager().sendVideoMessage(mContext, userIds.get(0), null,messageInfo.content,messageInfo.width, messageInfo.height,messageInfo.duration, messageInfo.countDown,new TgResultBlock<TgResponse>() {
                                        @Override
                                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                                            observer.onNext(obj);
                                            observer.onComplete();
                                        }

                                        @Override
                                        public void onTimeout(Map<String, Object> request) {
                                            observer.onNext(new TgResponse(false, "发送超时"));
                                            observer.onComplete();
                                        }
                                    });
                                }
                            });
                            emitter.onNext(observables);
                            emitter.onComplete();
                        }else{
                            EventBus.getDefault().register(GroupSendModule.this);
                            TelegramManager.getTelegramManager().sendVideoMessage(mContext, userIds.get(0), null,messageInfo.content,messageInfo.width, messageInfo.height,messageInfo.duration, messageInfo.countDown, tgResultBlock);
                        }

                    }else if(messageInfo.messageType == TelegramManager.MessageType.MessageType_Audio){
                        if(userIds.size()==1){
                            observables.add(new Observable<TgResponse>() {
                                @Override
                                protected void subscribeActual(Observer<? super TgResponse> observer) {
                                    TelegramManager.getTelegramManager().sendAudioMessage(mContext, userIds.get(0), messageInfo.content, (int) messageInfo.duration, messageInfo.countDown,new TgResultBlock<TgResponse>() {
                                        @Override
                                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                                            observer.onNext(obj);
                                            observer.onComplete();
                                        }

                                        @Override
                                        public void onTimeout(Map<String, Object> request) {
                                            observer.onNext(new TgResponse(false, "发送超时"));
                                            observer.onComplete();
                                        }
                                    });
                                }
                            });
                            emitter.onNext(observables);
                            emitter.onComplete();
                        }else{
                            EventBus.getDefault().register(GroupSendModule.this);
                            TelegramManager.getTelegramManager().sendAudioMessage(mContext, userIds.get(0), messageInfo.content, (int)messageInfo.duration, messageInfo.countDown,tgResultBlock);
                        }

                    }
                }

            }
        });
    }

    public void onDestory(){
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }
}
